package cn.stylefeng.guns.modular.hx.storage.controller;

import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.hx.storage.entity.HxCollectingCenter;
import cn.stylefeng.guns.modular.hx.storage.entity.HxCollectionLocation;
import cn.stylefeng.guns.modular.hx.storage.entity.HxStorageOut;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxCollectingCenterParam;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxCollectionLocationParam;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxStorageCenterParam;
import cn.stylefeng.guns.modular.hx.storage.model.result.HxCollectingCenterResult;
import cn.stylefeng.guns.modular.hx.storage.model.result.HxCollectionLocationResult;
import cn.stylefeng.guns.modular.hx.storage.service.HxCollectingCenterService;
import cn.stylefeng.guns.modular.hx.storage.service.HxCollectionLocationService;
import cn.stylefeng.guns.modular.hx.storage.service.HxStorageOutService;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.LambdaQueryChainWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static javax.xml.bind.DatatypeConverter.parseInt;


/**
 * 控制器
 *
 * @author lww
 * @Date 2024-01-02 11:00:46
 */
@Controller
@RequestMapping("/hxCollectingCenter")
public class HxCollectingCenterController extends BaseController {

    private String PREFIX = "/hx/storage/hxCollectingCenter";

    @Autowired
    private HxCollectingCenterService hxCollectingCenterService;
    @Autowired
    private HxCollectionLocationService hxCollectionLocationService;

    @Autowired
    private UserService userService;
    @Autowired
    private HxStorageOutService hxStorageOutService;

    /**
     * 跳转到主页面
     *
     * @author lww
     * @Date 2024-01-02
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "/hxCollectingCenter.html";
    }

    /**
     * 新增页面
     *
     * @author lww
     * @Date 2024-01-02
     */
    @RequestMapping("/add")
    public String add() {
        return PREFIX + "/hxCollectingCenter_add.html";
    }

    /**
     * 编辑页面
     *
     * @author lww
     * @Date 2024-01-02
     */
    @RequestMapping("/edit")
    public String edit(String stockPort, Model model) {
        User user = userService.getcurrentUser();
        HxCollectingCenterParam q = new HxCollectingCenterParam();
        HxCollectionLocationParam q1 = new HxCollectionLocationParam();
        if (user.getOperateId() != null) {
            q.setOperateId(user.getOperateId());
            q1.setOperateId(user.getOperateId());

        }
        if (user.getDeptId() != null) {
            q.setDeptId(user.getDeptId());
            q1.setDeptId(user.getDeptId());
        }
        List<HxCollectingCenterResult> HxCollectingLists = this.hxCollectingCenterService.findListBySpec(q);
        q1.setStockPort(stockPort.split("-")[1]);
        q1.setStatus("已占用");
        List<HxCollectionLocationResult> locationLists1 = this.hxCollectionLocationService.findListBySpec(q1);
        model.addAttribute("HxCollectingLists", HxCollectingLists);
        model.addAttribute("locationLists1", locationLists1);

        return PREFIX + "/hxCollectingCenter_edit.html";
    }

    @RequestMapping("/edit2")
    public String edit2(String stockPort, Model model) {
        User user = userService.getcurrentUser();
        HxCollectingCenterParam q = new HxCollectingCenterParam();
        if (user.getOperateId() != null) {
            q.setOperateId(user.getOperateId());
        }
        if (user.getDeptId() != null) {
            q.setDeptId(user.getDeptId());
        }
        List<HxCollectingCenterResult> HxCollectingLists = this.hxCollectingCenterService.findListBySpec(q);
        model.addAttribute("HxCollectingLists", HxCollectingLists);
        return PREFIX + "/hxCollectingCenter_edit2.html";
    }

    /**
     * 新增接口
     *
     * @author lww
     * @Date 2024-01-02
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(HxCollectingCenterParam hxCollectingCenterParam) {
        this.hxCollectingCenterService.add(hxCollectingCenterParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     *
     * @author lww
     * @Date 2024-01-02
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(HxCollectingCenterParam hxCollectingCenterParam) {
        hxCollectingCenterParam.setGetUnit("");
        hxCollectingCenterParam.setGetUnitId(null);
        this.hxCollectingCenterService.update(hxCollectingCenterParam);
        return ResponseData.success();
    }


    @RequestMapping("/zhuijia")
    @ResponseBody
    public ResponseData zhuijia(String stockPort) {
        return this.hxCollectingCenterService.zhuidan(stockPort);
    }

    @RequestMapping("/chongfen")
    @ResponseBody
    public ResponseData chongfen(String stockPort) {
        return this.hxCollectingCenterService.chongfen(stockPort);
    }

    @RequestMapping("/zhuanyi")
    @ResponseBody
    public ResponseData zhuanyi(HxCollectingCenterParam hxCollectingCenterParam) {
        User user = userService.getcurrentUser();
        HxCollectionLocationParam q = new HxCollectionLocationParam();
        q.setStockPort(hxCollectingCenterParam.getStockPort());
        q.setLocation(hxCollectingCenterParam.getLocation());
        if (user.getOperateId() != null) {
            q.setOperateId(user.getOperateId());
            hxCollectingCenterParam.setOperateId(user.getOperateId());
        }
        if (user.getDeptId() != null) {
            q.setDeptId(user.getDeptId());
            hxCollectingCenterParam.setDeptId(user.getDeptId());
        }
        //目标位是否已有货物
        //判断分配的通道 是否已有被占用
        q.setGetUnitIsNotNull("NOTNULL");
        List<HxCollectionLocationResult> listBySpec = hxCollectionLocationService.findListBySpec(q);
        if (listBySpec != null && listBySpec.size() > 0) {
            return ResponseData.error("已被其他门店占用，请使用其他位置！");
        }

        this.hxCollectingCenterService.zhuanyi(hxCollectingCenterParam);
        return ResponseData.success();
    }

    @RequestMapping("/zhuanyi2")
    @ResponseBody
    public ResponseData zhuanyi2(HxCollectingCenterParam hxCollectingCenterParam) {
        User user = userService.getcurrentUser();
        HxCollectionLocationParam q = new HxCollectionLocationParam();
        q.setStockPort(hxCollectingCenterParam.getStockPort());
        if (user.getOperateId() != null) {
            q.setOperateId(user.getOperateId());
            hxCollectingCenterParam.setOperateId(user.getOperateId());
        }
        if (user.getDeptId() != null) {
            q.setDeptId(user.getDeptId());
            hxCollectingCenterParam.setDeptId(user.getDeptId());
        }
        //目标位是否已有货物
        //判断分配的通道 是否已有被占用
        q.setGetUnitIsNotNull("NOTNULL");
        List<HxCollectionLocationResult> listBySpec = hxCollectionLocationService.findListBySpec(q);
        if (listBySpec != null && listBySpec.size() > 0) {
            return ResponseData.error("已被其他门店占用，请使用其他位置！");
        }

        this.hxCollectingCenterService.zhuanyi2(hxCollectingCenterParam);
        return ResponseData.success();
    }

    /**
     * 删除接口
     *
     * @author lww
     * @Date 2024-01-02
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(HxCollectingCenterParam hxCollectingCenterParam) {
        this.hxCollectingCenterService.delete(hxCollectingCenterParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     *
     * @author lww
     * @Date 2024-01-02
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(HxCollectingCenterParam hxCollectingCenterParam) {
        HxCollectingCenter detail = this.hxCollectingCenterService.getById(hxCollectingCenterParam.getId());
        return ResponseData.success(detail);
    }

    /**
     * 查询列表
     *
     * @author lww
     * @Date 2024-01-02
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(HxCollectingCenterParam hxCollectingCenterParam, String condition) {
        User user = userService.getcurrentUser();
        hxCollectingCenterParam.setDeptId(user.getDeptId());
        hxCollectingCenterParam.setDeliverId(user.getDeliverId());
        return this.hxCollectingCenterService.findPageBySpec(hxCollectingCenterParam, condition);
    }

    @ResponseBody
    @RequestMapping("/cha")
    public List<HxCollectionLocationResult> cha(HxCollectingCenterParam hxCollectingCenterParam) {
        User user = userService.getcurrentUser();
        hxCollectingCenterParam.setDeptId(user.getDeptId());
        hxCollectingCenterParam.setOperateId(user.getOperateId());
        return this.hxCollectingCenterService.cha(hxCollectingCenterParam);
    }

    @RequestMapping("/fpstockPort")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public ResponseData fpstockPort(Long getUnitId, String stockPorts, String getUnit, Integer singleQuantity) throws Exception {

        User user = userService.getcurrentUser();

        if (ToolUtil.isEmpty(stockPorts)) {
            return ResponseData.error("请输入要分配的巷道！");
        }
        //更新通道表  门店名称
        String[] strs = stockPorts.split(",");

        //判断分配的通道 是否已有被占用
        HxCollectionLocationParam q = new HxCollectionLocationParam();
        q.setStockPorts(strs);
//        q.setGetUnitIsNotNull("notNull");
        if (user.getDeptId() != null) {
            q.setDeptId(user.getDeptId());
        }
        if (user.getOperateId() != null) {
            q.setOperateId(user.getOperateId());
        }

        Map<String,Integer> strsMap = new HashMap<>();
        List<HxCollectionLocationResult> listBySpec = hxCollectionLocationService.findListBySpec(q);
        if(listBySpec == null || listBySpec.size() < 1){
            return ResponseData.error("输入的集货通道不存在，请检查后重试！");
        }
        for(HxCollectionLocationResult obj : listBySpec){
            if(ToolUtil.isNotEmpty(obj.getGetUnitId())){
                return ResponseData.error("巷道已被其他门店占用，请使用其他巷道！");
            }
            if(strsMap.get(obj.getStockPort()) == null){
                strsMap.put(obj.getStockPort(),1);
            }else{
                strsMap.put(obj.getStockPort(),strsMap.get(obj.getStockPort()) + 1);
            }
        }

        if(strsMap.size() != strs.length){
            return ResponseData.error("分配的巷道信息与集货中心实际巷道不符，请检查后重试！");
        }

        LambdaQueryChainWrapper<HxStorageOut> select1 = hxStorageOutService.lambdaQuery()
                .eq(HxStorageOut::getGetUnitId, getUnitId)
                .eq(HxStorageOut::getDeptId, user.getDeptId())
                .and(item ->item.eq(HxStorageOut::getStockPort, "").or().isNull(HxStorageOut::getStockPort))
                .eq(HxStorageOut::getStorageState, "待拣货")
                .select();
        List<HxStorageOut> lists = new ArrayList<>();
        lists.addAll(select1.list());
        int outCnt = lists.size();
        if (outCnt > listBySpec.size()) {
            return ResponseData.error("单量大于通道容量,无法分配！");
        }

        int tongdaoIdx = 0;
        int locationIdx = 0;
        int cnt = strsMap.get(strs[tongdaoIdx]);
        for (HxStorageOut obj : lists) {
            locationIdx ++;
            hxStorageOutService.lambdaUpdate()
                    .set(HxStorageOut::getStockPort, strs[tongdaoIdx])
                    .eq(HxStorageOut::getId, obj.getId())
                    .update();
            hxCollectionLocationService.lambdaUpdate()
                    .set(HxCollectionLocation::getStatus, "已分配")
                    .set(HxCollectionLocation::getGetUnitId, getUnitId)
                    .set(HxCollectionLocation::getGetUnit, getUnit)
                    .set(HxCollectionLocation::getTrayId,obj.getId())
                    .eq(HxCollectionLocation::getDeptId, user.getDeptId())
                    .eq(HxCollectionLocation::getStockPort, strs[tongdaoIdx])
                    .eq(HxCollectionLocation::getLocation, locationIdx)
                    //.isNull(HxCollectionLocation::getStatus)
                    .update();
            cnt--;
            if(cnt < 1){
                tongdaoIdx ++;
                if(strs.length > tongdaoIdx){
                    cnt = strsMap.get(strs[tongdaoIdx]);
                    locationIdx = 0;
                }
            }
        }
        //更新拣货任务表   备货口
//        UpdateWrapper<HxStorageOut> updateWrapper = new UpdateWrapper<HxStorageOut>();
//        updateWrapper.set("stock_port", stockPorts);
//        updateWrapper.eq("get_unit_id", getUnitId);
//        hxStorageOutService.update(updateWrapper);
        return ResponseData.success();
    }

    @RequestMapping("/insertstockPort")
    @ResponseBody
    public ResponseData insertstockPort(String stockports, String locations) {
        User user = userService.getcurrentUser();
        //System.out.println(stockports);
        //新增备货口表  备货口
        String[] strs = stockports.split("-");
        //System.out.println(strs);
        int start = parseInt(strs[0]);
        //System.out.println(start);
        int end = parseInt(strs[1]);
        //System.out.println(end);
        if (start < end) {
            for (int i = start; i <= end; i++) {
                HxCollectingCenterParam hxCollectingCenterParam = new HxCollectingCenterParam();

                String s = String.valueOf(i);


                hxCollectingCenterParam.setStockPort(s);
                hxCollectingCenterParam.setDeptId(user.getDeptId());
                hxCollectingCenterParam.setDeliverId(user.getDeliverId());
                hxCollectingCenterParam.setOperateId(user.getOperateId());

                Long ck = hxCollectingCenterService.chaStockPortId(hxCollectingCenterParam);
                if (ck == null) {
                    hxCollectingCenterService.insertStockPort(hxCollectingCenterParam);

                    // 添加集货位信息到集货位表
                    for (int j = 1; j <= parseInt(locations); j++) {
                        HxCollectionLocationParam hxCollectionLocationParam = new HxCollectionLocationParam();
                        String ss = String.valueOf(j);
                        hxCollectionLocationParam.setStockPort(s);
                        HxCollectingCenterParam hxCollectingCenterParam1 = new HxCollectingCenterParam();
                        hxCollectingCenterParam1.setOperateId(user.getOperateId());
                        hxCollectingCenterParam1.setDeptId(user.getDeptId());
                        hxCollectingCenterParam1.setStockPort(s);
                        Long StockPortId = hxCollectingCenterService.chaStockPortId(hxCollectingCenterParam1);
                        hxCollectionLocationParam.setStockPortId(StockPortId);
                        hxCollectionLocationParam.setLocation(ss);
                        hxCollectionLocationParam.setDeptId(user.getDeptId());
                        hxCollectionLocationParam.setDeliverId(user.getDeliverId());
                        hxCollectingCenterService.insertCollectionLocation(hxCollectionLocationParam);
                    }
                } else {
                    return ResponseData.error("备货口已存在，无法重复添加");
                }
            }
        } else if (start >= end) {
            return ResponseData.error("添加格式错误");
        }
        return ResponseData.success();
    }

}




